import React, { useState, useEffect, useRef } from 'react';
import { useQuery, useMutation, useQueryClient } from 'react-query';
import { Users } from 'api/queries';
import { setAccountTrialPeriod } from 'api/mutations';

// MUI Components
import {
  Box,
  Button,
  Container,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Divider,
  FormControl,
  FormHelperText,
  Grid,
  IconButton,
  InputLabel,
  MenuItem,
  Paper,
  Select,
  Typography,
  CircularProgress,
  Accordion,
  AccordionSummary,
  AccordionDetails,
  Alert,
  Chip
} from '@mui/material';

// MUI Icons
import CloseIcon from '@mui/icons-material/Close';
import NorthIcon from '@mui/icons-material/North';
import SouthIcon from '@mui/icons-material/South';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import HistoryIcon from '@mui/icons-material/History';
import RefreshIcon from '@mui/icons-material/Refresh';

const ApiLogEvent = ({ event, onClose }) => {
  if (!event) return null;
  
  const isSuccess = event.type === 'response' && event.status >= 200 && event.status < 300;
  const isError = event.type === 'response' && (event.status < 200 || event.status >= 300);
  
  return (
    <Dialog 
      open={true} 
      onClose={onClose} 
      maxWidth="md" 
      fullWidth
    >
      <DialogTitle>
        <Box display="flex" alignItems="center" justifyContent="space-between">
          <Box display="flex" alignItems="center">
            {event.type === 'request' ? (
              <NorthIcon color="primary" sx={{ mr: 1 }} />
            ) : (
              <SouthIcon color={isSuccess ? "success" : "error"} sx={{ mr: 1 }} />
            )}
            <Typography variant="h6">
              {event.type === 'request' ? 'API Request' : 'API Response'}
            </Typography>
          </Box>
          <IconButton edge="end" onClick={onClose} aria-label="close">
            <CloseIcon />
          </IconButton>
        </Box>
      </DialogTitle>
      <DialogContent dividers>
        {event.type === 'request' && (
          <Box mb={2}>
            <Paper variant="outlined" sx={{ p: 2 }}>
              <Typography variant="subtitle1" fontWeight="bold" gutterBottom>
                Request Details
              </Typography>
              <Box mt={1} display="flex" alignItems="center">
                <Chip 
                  label={event.method?.toUpperCase() || 'GET'} 
                  color="primary" 
                  size="small" 
                  sx={{ mr: 1 }} 
                />
                <Typography variant="body2" fontFamily="monospace">
                  {event.url || 'Unknown URL'}
                </Typography>
              </Box>
              
              {event.data && (
                <Box mt={2}>
                  <Typography variant="body2" fontWeight="medium">
                    Request Body:
                  </Typography>
                  <Paper 
                    variant="outlined" 
                    sx={{ 
                      mt: 1, 
                      p: 1.5, 
                      maxHeight: '200px', 
                      overflow: 'auto' 
                    }}
                  >
                    <pre style={{ margin: 0, fontSize: '0.75rem' }}>
                      {JSON.stringify(event.data, null, 2)}
                    </pre>
                  </Paper>
                </Box>
              )}
            </Paper>
          </Box>
        )}
        
        {event.type === 'response' && (
          <Box>
            <Paper variant="outlined" sx={{ p: 2, mb: 2 }}>
              <Typography variant="subtitle1" fontWeight="bold" gutterBottom>
                Response Details
              </Typography>
              <Box mt={1} display="flex" alignItems="center">
                <Chip 
                  label={event.status || '???'} 
                  color={isSuccess ? "success" : "error"} 
                  size="small" 
                  sx={{ mr: 1 }} 
                />
                <Typography variant="body2" fontFamily="monospace">
                  {event.statusText || 'Unknown Status'}
                </Typography>
              </Box>
            </Paper>
            
            <Box mb={2}>
              <Typography variant="subtitle2" gutterBottom>
                Response Data:
              </Typography>
              <Paper 
                variant="outlined" 
                sx={{ 
                  p: 2, 
                  maxHeight: '300px', 
                  overflow: 'auto',
                  bgcolor: 'action.hover'
                }}
              >
                <pre style={{ margin: 0, fontSize: '0.75rem' }}>
                  {JSON.stringify(event.data, null, 2)}
                </pre>
              </Paper>
            </Box>
            
            {event.headers && (
              <Accordion variant="outlined">
                <AccordionSummary expandIcon={<ExpandMoreIcon />}>
                  <Typography variant="subtitle2">Response Headers</Typography>
                </AccordionSummary>
                <AccordionDetails>
                  <Paper 
                    variant="outlined" 
                    sx={{ 
                      p: 2, 
                      maxHeight: '200px', 
                      overflow: 'auto',
                      bgcolor: 'action.hover' 
                    }}
                  >
                    <pre style={{ margin: 0, fontSize: '0.75rem' }}>
                      {JSON.stringify(event.headers, null, 2)}
                    </pre>
                  </Paper>
                </AccordionDetails>
              </Accordion>
            )}
          </Box>
        )}
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>Close</Button>
      </DialogActions>
    </Dialog>
  );
};

const SimpleTrialRefreshPage = () => {
  const [selectedUserId, setSelectedUserId] = useState('');
  const [selectedAccountId, setSelectedAccountId] = useState('');
  const [apiEvents, setApiEvents] = useState([]);
  const [currentEvent, setCurrentEvent] = useState(null);
  const [openLogDialog, setOpenLogDialog] = useState(false);
  const queryClient = useQueryClient();
  const isMounted = useRef(true);
  
  // Add API events to our log
  const logApiEvent = (event) => {
    setApiEvents(prev => [...prev, event]);
    setCurrentEvent(event);
  };
  
  // Clear current event popup
  const clearCurrentEvent = () => {
    setCurrentEvent(null);
  };
  
  // Handle Users query with API logging
  const { data: axiosResponse, isLoading, error } = useQuery('AllUsers', Users, {
    onSuccess: (data) => {
      if (isMounted.current) {
        // Log API response event
        logApiEvent({
          type: 'response',
          url: data.config?.url || '/users/',
          status: data.status,
          statusText: data.statusText,
          data: data.data,
          headers: data.headers,
          timestamp: new Date().toISOString()
        });
      }
    },
    onError: (err) => {
      if (isMounted.current) {
        // Log API error event
        logApiEvent({
          type: 'response',
          url: '/users/',
          status: err.response?.status || 500,
          statusText: err.response?.statusText || err.message,
          data: err.response?.data || { error: err.message },
          timestamp: new Date().toISOString()
        });
      }
    }
  });
  
  // Log initial API request event when the component mounts
  useEffect(() => {
    isMounted.current = true;
    
    // Log the initial API request
    logApiEvent({
      type: 'request',
      method: 'GET',
      url: '/users/',
      timestamp: new Date().toISOString()
    });
    
    return () => {
      isMounted.current = false;
    };
  }, []);
  
  // Extract the actual users array from the Axios response
  const usersArray = axiosResponse?.data || [];
  
  const handleUserChange = (event) => {
    const userId = event.target.value;
    setSelectedUserId(userId);
    
    // Find the selected user's account ID
    if (userId && usersArray.length > 0) {
      const user = usersArray.find(u => u.id === userId);
      if (user && user.accountId) {
        setSelectedAccountId(user.accountId);
      } else {
        setSelectedAccountId('');
      }
    } else {
      setSelectedAccountId('');
    }
  };
  
  // Mutation for setting trial period with API logging
  const setTrialMutation = useMutation(
    ({ accountId, days }) => {
      // Log API request event
      const requestData = { trialDays: days };
      const requestUrl = `/accounts/${accountId}/trial`;
      
      logApiEvent({
        type: 'request',
        method: 'PUT',
        url: requestUrl,
        data: requestData,
        timestamp: new Date().toISOString()
      });
      
      return setAccountTrialPeriod(accountId, days);
    },
    {
      onSuccess: (data) => {
        // Log API response event
        logApiEvent({
          type: 'response',
          url: data.config?.url || `/accounts/${selectedAccountId}/trial`,
          status: data.status,
          statusText: data.statusText,
          data: data.data,
          headers: data.headers,
          timestamp: new Date().toISOString()
        });
        
        // Reset selection and refetch users
        setSelectedUserId('');
        setSelectedAccountId('');
        queryClient.invalidateQueries('AllUsers');
      },
      onError: (err) => {
        // Log API error event
        logApiEvent({
          type: 'response',
          url: `/accounts/${selectedAccountId}/trial`,
          status: err.response?.status || 500,
          statusText: err.response?.statusText || err.message,
          data: err.response?.data || { error: err.message },
          timestamp: new Date().toISOString()
        });
      }
    }
  );
  
  const handleRefreshTrial = () => {
    if (selectedAccountId) {
      // Set trial period to 3 days
      setTrialMutation.mutate({ accountId: selectedAccountId, days: 3 });
    }
  };
  
  // View API log history
  const showApiLogHistory = () => {
    setOpenLogDialog(true);
  };
  
  const handleCloseLogDialog = () => {
    setOpenLogDialog(false);
  };
  
  if (isLoading) return (
    <Box display="flex" justifyContent="center" alignItems="center" height="100vh">
      <CircularProgress />
      <Typography variant="h6" sx={{ ml: 2 }}>
        Loading users...
      </Typography>
    </Box>
  );
  
  if (error) return (
    <Box display="flex" justifyContent="center" alignItems="center" height="100vh">
      <Alert severity="error" sx={{ maxWidth: 600 }}>
        <Typography variant="subtitle1">
          Error loading users: {error.message}
        </Typography>
      </Alert>
    </Box>
  );
  
  return (
    <Container maxWidth="sm" sx={{ py: 4 }}>
      <Paper elevation={2} sx={{ p: 3 }}>
        <Typography variant="h5" gutterBottom align="center" fontWeight="bold">
          Refresh User Trial
        </Typography>
        
        <Divider sx={{ my: 2 }} />
        
        <FormControl fullWidth sx={{ mb: 3 }}>
          <InputLabel id="user-select-label">Select User</InputLabel>
          <Select
            labelId="user-select-label"
            value={selectedUserId}
            onChange={handleUserChange}
            label="Select User"
            disabled={isLoading || setTrialMutation.isLoading}
          >
            <MenuItem value="">
              <em>Select a user</em>
            </MenuItem>
            {usersArray && usersArray.length > 0 ? (
              usersArray.map(user => (
                <MenuItem key={user.id} value={user.id}>
                  {user.email}
                </MenuItem>
              ))
            ) : (
              <MenuItem disabled>No users available</MenuItem>
            )}
          </Select>
          <FormHelperText>
            {selectedAccountId ? `Account ID: ${selectedAccountId}` : ''}
          </FormHelperText>
        </FormControl>
        
        <Box display="flex" justifyContent="center" mb={2}>
          <Button
            variant="contained"
            color="primary"
            size="large"
            disabled={!selectedAccountId || setTrialMutation.isLoading}
            onClick={handleRefreshTrial}
            startIcon={setTrialMutation.isLoading ? <CircularProgress size={24} color="inherit" /> : <RefreshIcon />}
          >
            {setTrialMutation.isLoading ? 'Refreshing...' : 'Refresh Trial (3 Days)'}
          </Button>
        </Box>
        
        <Box display="flex" justifyContent="center" mt={3}>
          <Button
            variant="text"
            color="primary"
            startIcon={<HistoryIcon />}
            onClick={showApiLogHistory}
            size="small"
          >
            Show API Log History ({apiEvents.length})
          </Button>
        </Box>
      </Paper>
      
      {/* API Log History Dialog */}
      <Dialog
        open={openLogDialog}
        onClose={handleCloseLogDialog}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>
          <Box display="flex" alignItems="center" justifyContent="space-between">
            <Typography variant="h6">
              API Log History ({apiEvents.length} events)
            </Typography>
            <IconButton edge="end" onClick={handleCloseLogDialog}>
              <CloseIcon />
            </IconButton>
          </Box>
        </DialogTitle>
        <DialogContent dividers>
          {apiEvents.map((event, index) => (
            <Box 
              key={index} 
              mb={1} 
              p={1} 
              borderRadius={1}
              sx={{
                cursor: 'pointer',
                '&:hover': { 
                  opacity: 0.8 
                }
              }}
              onClick={() => {
                setCurrentEvent(event);
                handleCloseLogDialog();
              }}
            >
              <Grid container alignItems="center" spacing={1}>
                <Grid item>
                  {event.type === 'request' ? (
                    <NorthIcon color="primary" fontSize="small" />
                  ) : (
                    <SouthIcon 
                      color={
                        event.status >= 200 && event.status < 300 
                          ? "success" 
                          : "error"
                      } 
                      fontSize="small" 
                    />
                  )}
                </Grid>
                <Grid item>
                  <Chip 
                    label={event.method || (event.type === 'response' ? 'RES' : 'REQ')} 
                    size="small" 
                    color={event.type === 'request' ? "primary" : "default"}
                    variant={event.type === 'request' ? "filled" : "outlined"}
                  />
                </Grid>
                <Grid item xs>
                  <Typography variant="body2" noWrap>
                    {event.url}
                  </Typography>
                </Grid>
                <Grid item>
                  {event.type === 'response' && (
                    <Chip 
                      label={event.status} 
                      size="small"
                      color={
                        event.status >= 200 && event.status < 300 
                          ? "success" 
                          : "error"
                      }
                    />
                  )}
                </Grid>
                <Grid item>
                  <Typography variant="caption" color="textSecondary">
                    {new Date(event.timestamp).toLocaleTimeString()}
                  </Typography>
                </Grid>
              </Grid>
            </Box>
          ))}
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseLogDialog}>Close</Button>
        </DialogActions>
      </Dialog>
      
      {/* Current API Event Popup */}
      {currentEvent && (
        <ApiLogEvent 
          event={currentEvent}
          onClose={clearCurrentEvent}
        />
      )}
    </Container>
  );
};

export default SimpleTrialRefreshPage;